<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/26
 * Time: 18:02
 */
namespace App\Http\Controllers\web;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntMemberInfo;
use App\Module\EntMobileCode;
use App\Module\EntBookRenewLog;
use App\Module\EntMemberDRP;
use App\Module\EntPushMoneyLog;
use App\Module\EntOrderPrepaidLog;
use Session;
use Redirect, Validator, Cookie, Response, DB;

class TLoginController extends Controller
{
    protected $scaleOne = '0.3';
    protected $scaleTwo = '0.05';
    protected $scaleMoney = '2000';

    public function checkUser()
    {
        //$xml = simplexml_load_file('XMLFile.xml');

//        $up=$xml->xpath("/xml/Access_Token");添加节点
//        $up[0]->Access_Token='aaa';

//        $xml->Access_Token='aaa';//修改不节点
//        $xml->asXML('XMLFile.xml');
//        $accessToken=$xml->Access_Token;
        // $accessToken=env('WEIXIN_APPID');
        //       Session::put('OPENID', 'o2aI9weLjZa5RogQd0Fo4AiPU7_M');
        $MOpenid = Session::get('OPENID');
//        $memberInfo = $this->checkMemberInfo(2, $MOpenid);
//        $zero1 = date('Y-m-d H:i:s');
//        $zero2 = $memberInfo->MemEndTime;
//        if (strtotime($zero1) < strtotime($zero2)) {
//            //未到期
//            $MOpenid = $MOpenid . '___1';
//        } else {
//            //到期
//            $MOpenid = $MOpenid . '___2';
//        }
        return view('login', ['OPENID' => $MOpenid]);
    }

    /*
     * 添加会员
     */
    public function loginstore(Request $request)
    {
        $MOpenid = Session::get('OPENID');

        if ($MOpenid != '') {

            $memberInfo = $this->checkMemberInfo(2, $MOpenid);
            if (count($memberInfo) > 0) {
                //判断是否已经缴纳会费
                if ($memberInfo->States == 0) {
                    $loginKey = md5(date('YmdHis', time()));
                    if ($loginKey != '') {
                        EntMemberInfo::where('MemNumber', $memberInfo->MemNumber)->where('States', 0)->update(['LoginKey' => $loginKey]);
                    }
                    Session::put('MName', $memberInfo->UserName);
                    Session::put('MKey', $loginKey);
                    return redirect('/pay/pay.html');
                } else {
                    $loginKey = md5(date('YmdHis', time()));
                    if ($loginKey != '') {
                        EntMemberInfo::where('MemNumber', $memberInfo->MemNumber)->where('States', 1)->update(['LoginKey' => $loginKey]);
                    }
                    Session::put('MName', $memberInfo->UserName);
                    Session::put('MKey', $loginKey);
                    return redirect('/book.html');
                }
            } else {
                $userName = trim($request->get('txtMobile'));
                $memberInfoTwo = $this->checkMemberInfo(1, $userName);
                if (count($memberInfoTwo) > 0) {
                    $loginKey = md5(date('YmdHis', time()));
                    if ($loginKey != '') {
                        EntMemberInfo::where('MemNumber', $memberInfoTwo->MemNumber)->where('States', 1)->update(['LoginKey' => $loginKey, 'WeiXID' => $MOpenid]);
                        Session::put('MName', $memberInfoTwo->UserName);
                        Session::put('MKey', $loginKey);
                        return redirect('/book.html');
                    } else {
                        return redirect::back()->withInput()->withErrors('服务器繁忙请稍后在试！');
                    }
                } else {
                    $i = 0;
                    $MemNumber = date('Ymd', time()) . '0' . mt_rand();
                    while ($i == 0) {
                        $checkNumber = EntMemberInfo::select('UserName')->where('MemNumber', $MemNumber)->first();
                        if (count($checkNumber) > 0) {
                            $MemNumber = date('Ymd', time()) . '0' . mt_rand();
                        } else {
                            $i = 1;
                        }
                    }
                    $loginKey = md5(date('YmdHis', time()));
                    $userName = trim($request->get('txtMobile'));
                    $entMemberInfo = new EntMemberInfo();
                    $entMemberInfo->States = 0;
                    $entMemberInfo->MemNumber = $MemNumber;
                    $entMemberInfo->UserName = $userName;
                    $entMemberInfo->YourName = trim($request->get('txtYourName'));
                    $entMemberInfo->UserPassWord = '';
                    $entMemberInfo->NickName = '';
                    $entMemberInfo->FilePath1 = '';
                    $entMemberInfo->WeiXID = $MOpenid;
                    $entMemberInfo->VipNumber = 1;
                    $entMemberInfo->MemIntegral = 0;
                    $entMemberInfo->LoginKey = $loginKey;
                    $entMemberInfo->MemEndTime = '';
                    $entMemberInfo->DeleteMark = 1;
                    $entMemberInfo->RegisterType = 2;
                    $entMemberInfo->ReleaseDate = date('Y-m-d H:i:s', time());
                    $entMemberInfo->AddDate = date('Y-m-d H:i:s', time());
                    $entMemberInfo->save();
                    if ($entMemberInfo) {
                        $DRPID = Session::get('DRPID');
                        if ($DRPID != '' && $DRPID != '1') {
                            $ParentID = $DRPID;
                            $entMemberDRP = new EntMemberDRP();
                            $entMemberDRP->MemNumber = $entMemberInfo->MemNumber;
                            $entMemberDRP->SalesMoney = 0;
                            $entMemberDRP->MemBalances = 0;
                            $entMemberDRP->FinishMoney = 0;
                            $entMemberDRP->DRPScale = '';
                            $entMemberDRP->DRPLevel = 2;
                            $entMemberDRP->IDTree = '.' . $ParentID . '.';
                            $entMemberDRP->ParentID = $ParentID;
                            $entMemberDRP->MasterID = 0;
                            $entMemberDRP->DeleteMark = 1;
                            $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                            $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                            $entMemberDRP->save();
                            if ($entMemberDRP) {
                                //修改DOP状态
                                DB::table('MemberDRP')->where('DRPID', $entMemberDRP->DRPID)->update(['IDTree' => $entMemberDRP->IDTree . $entMemberDRP->DRPID . '.']);
                            }
                            Session::put('MName', $userName);
                            Session::put('MKey', $loginKey);
                            return redirect('/testpay/pay.html');
                        }
                        Session::put('MName', $userName);
                        Session::put('MKey', $loginKey);
                        return redirect('/pay/pay.html');
                    } else {
                        return redirect::back()->withInput()->withErrors('服务器繁忙请稍后在试！');
                    }
                }
            }
        } else {
            return redirect::back()->withInput()->withErrors('服务器繁忙请稍后在试！');
        }
    }

    protected function checkMemberInfo($type, $name)
    {
        if ($type > 0) {
            switch ($type) {
                case 1:
                    $entMemberInfoOne = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime')->where('DeleteMark', '1')->where('UserName', $name)->first();
                    return $entMemberInfoOne;
                    break;
                case 2:
                    $entMemberInfoTwo = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime')->where('DeleteMark', '1')->where('WeiXID', $name)->first();
                    return $entMemberInfoTwo;
                    break;
            }
        } else {
            return '';
        }
    }


    public function pay()
    {
        $memNumber = $this->return_MemNumber();
        $str = $this->unifiedOrderXML();//返回统一下单所需的XML
        $mopenid = Session::get('OPENID');
        $prepay_id = $this->postUnifiedOrder($str);//返回prepay_id
        $payArray = $this->getPaySign($prepay_id);//支付所需参数
        $xmlOrder = simplexml_load_string($str);
        $out_trade_no = (string)$xmlOrder->out_trade_no;//订单
        $entOrderPrepaidLog = new EntOrderPrepaidLog();
        $entOrderPrepaidLog->WeiXID = $mopenid;
        $entOrderPrepaidLog->OrderNumber = $out_trade_no;
        $entOrderPrepaidLog->MemNumber = $memNumber;
        $entOrderPrepaidLog->AddDate = date('Y-m-d H:i:s', time());
        $entOrderPrepaidLog->save();
        return view('testpay.pay', compact('payArray', 'out_trade_no', 'mopenid', 'memNumber'));
    }

    public function paysuccess()
    {
        //$this->excel();
        return view('testpay.paysuccess');
    }

    //导入会员
    public function excel()
    {
        $str = "";
        if ($str != '') {
            $str2 = explode('|', $str);
            foreach ($str2 as $value) {
                if ($value != '') {
                    $i = 0;
                    $MemNumber = date('Ymd', time()) . '0' . mt_rand();
                    while ($i == 0) {
                        $checkNumber = EntMemberInfo::select('UserName')->where('MemNumber', $MemNumber)->first();
                        if (count($checkNumber) > 0) {
                            $MemNumber = date('Ymd', time()) . '0' . mt_rand();
                        } else {
                            $i = 1;
                        }
                    }
                    $str4 = explode('_', $value);
                    $strname = trim($str4[0]);
                    $entMemberInfo = new EntMemberInfo();
                    $entMemberInfo->States = 1;
                    $entMemberInfo->MemNumber = $MemNumber;
                    $entMemberInfo->UserName = trim($str4[1]);
                    $entMemberInfo->YourName = $strname;
                    $entMemberInfo->UserPassWord = '';
                    $entMemberInfo->NickName = $strname;
                    $entMemberInfo->FilePath1 = '';
                    $entMemberInfo->VipNumber = 1;
                    $entMemberInfo->LoginKey = md5(date('YmdHis', time()));
                    $entMemberInfo->WeiXID = '';
                    $entMemberInfo->DeleteMark = 1;
                    $entMemberInfo->MemEndTime = '2017-10-01 00:00:00';
                    $entMemberInfo->ReleaseDate = date('Y-m-d H:i:s', time());
                    $entMemberInfo->AddDate = date('Y-m-d H:i:s', time());
                    $entMemberInfo->save();
                }
            }
        }
        return view('excel');
    }

    public function mobiletest()
    {
        //$this->excel();
        //$nonceStr=str_random(20);//随机字符串
        $str = $this->unifiedOrderXML(); //$this->timeStamp();
        $prepay_id = $this->postUnifiedOrder($str);
        $payArray = $this->getPaySign($prepay_id);
        return view('mobiletest', ['str' => $prepay_id]);
    }

    /**获取prepay_id
     * @param $para  统一下单XML
     * @return \SimpleXMLElement[]|string
     */
    protected function postUnifiedOrder($para)
    {
        $prepay_id = '';
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $responseText = $this->getHttpResponsePOST($url, $para);
        if ($responseText != '') {
            $xmlUnifiedOrder = simplexml_load_string($responseText);
            $prepay_id = (string)$xmlUnifiedOrder->prepay_id;
        }
        return $prepay_id;
    }

    /**生成统一下单参数
     * @return string 返回XML
     */
    protected function unifiedOrderXML()
    {
        $MOpenid = Session::get('OPENID');
        $appid = env('WEIXIN_APPID');//公众账号ID
        $mch_id = '1407661602';//商户号

        $device_info = 'WEB';//设备号--否
        $nonce_str = str_random(20);//随机字符串
        $sign = '';//签名
        $body = '老侯代读会费';//商品描述
        //$detail = '';//商品详情 --否

        $attach = '老侯代读会费';//附加数据 --否
        $out_trade_no = 'cz' . date('YmdHis', time()) . $this->RandStr(3);//商户订单号
        $fee_type = 'CNY';//货币类型 --否
        $total_fee = '200000';//总金额
        $spbill_create_ip = $this->get_real_ip();//终端IP
        $time_start = date('YmdHis', time());//交易起始时间 --否yyyyMMddHHmmss
        //$time_expire = '';//交易结束时间 --否yyyyMMddHHmmss

        //$goods_tag = '';//商品标记 --否
        $notify_url = 'http://wx.laohoulundao.com/pay/wxnotifyurl';//通知地址
        $trade_type = 'JSAPI';//交易类型
        //$product_id = '';//商品ID --否
        //$limit_pay = '';//指定支付方式 --否
        $openid = $MOpenid;//用户标识 --否
        $orderXml = ['appid' => $appid, 'mch_id' => $mch_id, 'device_info' => $device_info, 'nonce_str' => $nonce_str, 'sign' => $sign, 'body' => $body, 'attach' => $attach, 'out_trade_no' => $out_trade_no, 'fee_type' => $fee_type, 'total_fee' => $total_fee, 'spbill_create_ip' => $spbill_create_ip, 'time_start' => $time_start, 'notify_url' => $notify_url, 'trade_type' => $trade_type, 'openid' => $openid];

        $orderXml['sign'] = $this->getSign($orderXml);
        //return strtoupper(md5($orderXmlSortStr));
        return $this->foreachXML($orderXml);
    }

    /** 拼接XML
     * @param $array 统一下单参数
     * @return string
     */
    protected function foreachXML($array)
    {
        $xml = '<xml>';
        if (count($array) > 0) {
            foreach ($array as $key => $val) {
                if ($val != '') {
                    $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
                }
            }
        }
        return $xml . '</xml>';
    }

    /**生成签名
     * @param $array 统一下单参数
     * @return string--获取 prepay_id 签名
     */
    protected function getSign($array)
    {
        /**
         * 生成sign签名
         * 注：签名不能包含sign以及空的值
         */
        $orderXmlSortStr = '';
        $orderXmlSort = array_sort_recursive($array);

        foreach ($orderXmlSort as $key => $val) {
            if ($val != '' && $key != 'sign') {
                $orderXmlSortStr .= $key . '=' . $val . '&';
            }
        }
        return strtoupper(md5($orderXmlSortStr . 'key=' . env('WEIXIN_PAYKEY')));
    }

    /**生成支付数组
     * @param $prepay_id
     * @return string  返回 paySign 签名
     */
    protected function getPaySign($prepay_id)
    {
        $str = '';
        $appId = env('WEIXIN_APPID');
        $timeStamp = $this->timeStamp();
        $nonceStr = str_random(20);
        $package = 'prepay_id=' . $prepay_id;
        $signType = 'MD5';
        $paySign = '';
        $payArray = ['appId' => $appId, 'timeStamp' => $timeStamp, 'nonceStr' => $nonceStr, 'package' => $package, 'signType' => $signType, 'sign' => $paySign];
        $payArray['sign'] = $this->getSign($payArray);
        return $payArray;
    }

    /**时间戳
     * @return bool|string
     */
    protected function timeStamp()
    {
        return strtotime('now');
    }

    /**获取客户端IP
     * @return bool
     */
    protected function get_real_ip()
    {

        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * return 远程输出的数据
     */
    protected function getHttpResponseGET($url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);
        return $responseText;
    }

    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * @param $para 请求的数据
     * @param $input_charset 编码格式。默认值：空值
     * return 远程输出的数据
     */
    protected function getHttpResponsePOST($url, $para, $input_charset = '')
    {

        if (trim($input_charset) != '') {
            $url = $url . "_input_charset=" . $input_charset;
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $para);// post传输数据
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);

        return $responseText;
    }

    // 验证手机验证码
    public function addMobCode(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $userimgcode = '';
                $usermobile = $request->json('mobile');
                if ($usermobile != '') {
                    $entMobileCodeTime = EntMobileCode::select('EndTime', 'ID')->where('Mobile', $usermobile)
                        ->where('States', 1)
                        ->orderBy('AddDate', 'desc')
                        ->first();
                    if (count($entMobileCodeTime) > 0) {
                        $nowtime = date('Y-m-d h:i:s', time());
                        $endtime = $entMobileCodeTime->EndTime;
                        if (strtotime($nowtime) < strtotime($endtime)) {
                            // 时间没有到
                            $result = '2';
                        } else {
                            $Code = $this->RandStr(5);
                            if ($usermobile != '' && $Code != '') {
                                $now = date('Y-m-d h:i:s', time());
                                $entMobileCode = new EntMobileCode();
                                $entMobileCode->States = 1;
                                $entMobileCode->Mobile = $usermobile;
                                $entMobileCode->Code = $Code;
                                $entMobileCode->EndTime = date("Y-m-d H:i:s", strtotime("+2minutes", strtotime($now)));
                                $entMobileCode->AddDate = date('Y-m-d H:i:s', time());
                                $entMobileCode->save();
                                if ($entMobileCode) {
                                    $coment = $this->getMobileCode($usermobile, $Code);
                                    if ($coment != '') {
                                        $k = explode(',', $coment);
                                        $g = $k[0];
                                        if ($g == 0) {
                                            // 发送成功！
                                            $result = '3';
                                        } else {
                                            // 发送失败！
                                            $result = '4';
                                        }
                                    } else {
                                        $result = '4';
                                    }
                                }
                            } else {
                                // 短信发送失败
                                $result = '4';
                            }
                        }
                    } else {
                        $Code = $this->RandStr(5);
                        if ($usermobile != '' && $Code != '') {
                            $now = date('Y-m-d h:i:s', time());
                            $entMobileCode = new EntMobileCode();
                            $entMobileCode->States = 1;
                            $entMobileCode->Mobile = $usermobile;
                            $entMobileCode->Code = $Code;
                            $entMobileCode->EndTime = date("Y-m-d H:i:s", strtotime("+2minutes", strtotime($now)));
                            $entMobileCode->AddDate = date('Y-m-d H:i:s', time());
                            $entMobileCode->save();
                            if ($entMobileCode) {
                                $coment = $this->getMobileCode($usermobile, $Code);
                                if ($coment != '') {
                                    $k = explode(';', $coment);
                                    $g = $k[0];
                                    if ($g == 'OK') {
                                        // 发送成功！
                                        $result = '3';
                                    } else {
                                        // 发送失败！
                                        $result = '4';
                                    }
                                } else {
                                    $result = '4';
                                }
                            }
                        } else {
                            // 短信发送失败
                            $result = '4';
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $result = '4';
        }
        return $result;
    }

    // 验证手机验证码
    public function checkMobCode(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $userimgcode = '';
                $usermobcode = $request->json('mobcode');
                $usermobile = $request->json('mobile');

//                $entMemberInfo = EntMemberInfo::select('UserID')->where('UserName', $usermobile)
//                    ->where('DeleteMark', 1)
//                    ->get();
//                if (count($entMemberInfo) > 0) {
//                    // 您注册的账号已存在，请重新输入手机号码
//                    $result = '1';
//                } else {
//
//                }
                $mobileCode = EntMobileCode::select('ID')->where('Mobile', $usermobile)
                    ->where('States', 1)
                    ->where('Code', $usermobcode)
                    ->first();
                if (count($mobileCode) > 0) {
                    $delMobileCode = EntMobileCode::where('Mobile', $usermobile)->where('States', 1)
                        ->delete();
                    $result = '3';
                } else {
                    // 您输入的手机验证码不正确
                    $result = '2';
                }
            }
        } catch (Exception $e) {
            $result = '4';
        }
        return $result;
    }

    //随机数字
    protected function RandStr($n)
    {
        $s = '';
        $str = "123456789"; // 输出字符集
        $len = strlen($str) - 1;
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }

    protected function getMobileCode($mobile = '', $code = '')
    {
        $msg = '感谢您注册老侯代读！您本次的注册验证码为:' . $code . '。请及时验证注册！';
        $url = 'http://103.47.139.8/SHHL95/qxtinterface.aspx?phone=' . $mobile . '&message=' . iconv("UTF-8", "gb2312", $msg) . '&user=nanguash&pwd=laohou123';
        if (ini_get("allow_url_fopen") == "1") {
            $response = file_get_contents($url);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_URL, $url);
            $response = curl_exec($ch);
            curl_close($ch);
        }

        // -------请求为空
        if (empty($response)) {
            $this->error->showError("50001");
        }
        return $response;
    }

    /** 添加支付记录
     * @param Request $request
     * @return string 3-失败 1-成功
     */
    public function payOrderStore(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $order = $request->json('order');
                $MOpenid = Session::get('OPENID');
                $memNumber = $this->return_MemNumberTwo($MOpenid);
                if (count($memNumber) > 0) {
                    if ($memNumber->States == 0) {
                        if ($MOpenid != '' && $order != '' && $memNumber->MemNumber != '') {
                            $entBookRenewLog = new EntBookRenewLog();
                            $entBookRenewLog->MemNumber = $memNumber->MemNumber;
                            $entBookRenewLog->OrderNumber = $order;
                            $entBookRenewLog->RenewDesc = '会员缴费';
                            $entBookRenewLog->WeiXID = $MOpenid;
                            $entBookRenewLog->AddDate = date('Y-m-d H:i:s', time());
                            $entBookRenewLog->save();
                            if ($entBookRenewLog) {
                                EntMemberInfo::where('WeiXID', $MOpenid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                                $this->pushMoneyLogStore($memNumber->MemNumber);
                                $result = '1';
                            }
                        } else {
                            $result = '3';
                        }
                    } else {
                        $result = '1';
                    }
                } else {
                    $result = '3';
                }
            }
        } catch (Exception $e) {
            $result = '3';
        }
        return $result;
    }

    protected function return_MemNumber()
    {
        $i = 0;
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            if ($MName != '' && $MKey != '') {
                $entMemberInfo = EntMemberInfo::select('MemNumber', 'States')->where('UserName', $MName)->where('LoginKey', $MKey)
                    ->where('DeleteMark', '1')
                    ->first();
                if (count($entMemberInfo) > 0) {
                    $i = $entMemberInfo->MemNumber;
                }
            }
        } catch (ModelNotFoundException $e) {
            $i = 0;
        }
        return $i;
    }

    protected function return_MemNumberTwo($MOpenid)
    {
        $i = '';
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            if ($MName != '' && $MKey != '') {
                $entMemberInfo = EntMemberInfo::select('MemNumber', 'States')->where('UserName', $MName)->where('LoginKey', $MKey)
                    ->where('DeleteMark', '1')
                    ->first();
                if (count($entMemberInfo) > 0) {
                    $i = $entMemberInfo;
                }
            }
            if ($i == '') {
                $entMemberInfoTwo = EntMemberInfo::select('MemNumber', 'States')->where('WeiXID', $MOpenid)
                    ->where('DeleteMark', '1')
                    ->first();
                if (count($entMemberInfoTwo) > 0) {
                    $i = $entMemberInfoTwo;
                }
            }
        } catch (ModelNotFoundException $e) {
            $i = '';
        }
        return $i;
    }

    /**会员提点
     * @param string $memNumber
     */
    protected function pushMoneyLogStore($memNumber = '')
    {

        if ($memNumber != '') {

            $entMemberDRP = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID')->where('MemNumber', $memNumber)->first();
            if (count($entMemberDRP) > 0) {
                $parentID = $entMemberDRP->ParentID;
                if ($parentID > 0) {
                    $entMemberDRPTwo = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'SalesMoney', 'FinishMoney', 'MemBalances', 'MemNumber', 'IsRebate')->where('DRPID', $parentID)->first();
                    if (count($entMemberDRPTwo) > 0) {
                        $parentIDTwo = $entMemberDRPTwo->ParentID;
                        if ($parentIDTwo == 0) {
                            //返点30%
                            DB::beginTransaction();
                            try {
                                $money = $this->scaleMoney * $this->scaleOne;//600
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;//2000+0
                                //会员余额
                                // $MemBalances=$entMemberDRPTwo->MemBalances+$toalMoney;
                                // DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney,'MemBalances'=>$MemBalances]);
                                $IsFinish = 0;
                                if ($toalMoney > $entMemberDRPTwo->SalesMoney) {
                                    $IsFinish = 1;
                                }
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->IsFinish = $IsFinish;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $k = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $k = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $k = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $k = 2;
                                            } else {
                                                //提点+销售业绩
                                                $k = 3;
                                            }
                                        }

                                    }

                                } else {
                                    //销售业绩
                                    $k = 4;
                                }
                                switch ($k) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                DB::commit();
                            } catch (Exception $e) {
                                DB::rollBack();
                            }

                        } else {
                            $entMemberDRPTree = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'IsRebate', 'SalesMoney', 'MemBalances', 'FinishMoney', 'MemNumber')->where('DRPID', $parentIDTwo)->first();
                            if (count($entMemberDRPTree)) {
                                //返点30%
                                $money = $this->scaleMoney * $this->scaleOne;
                                //已完成销售金额
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;
                                //会员余额
                                // $MemBalances=$entMemberDRPTwo->MemBalances+$toalMoney;
                                //  DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney,'MemBalances'=>$MemBalances]);
                                $IsFinish = 0;
                                if ($toalMoney > $entMemberDRPTwo->SalesMoney) {
                                    $IsFinish = 1;
                                }
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->IsFinish = $IsFinish;
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $j = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $j = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $j = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $j = 2;
                                            } else {
                                                //提点+销售业绩
                                                $j = 3;
                                            }
                                        }

                                    }

                                } else {
                                    //销售业绩
                                    $j = 4;
                                }
                                switch ($j) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                //返点5%
                                $moneyTwo = $this->scaleMoney * $this->scaleTwo;
                                //$toalMoneyTwo = $moneyTwo + $entMemberDRPTree->FinishMoney;
                                if ($entMemberDRPTree->FinishMoney >= $entMemberDRPTree->SalesMoney) {
                                    if ($entMemberDRPTree->IsRebate == 0) {
                                        $memBalances = $entMemberDRPTree->SalesMoney + $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances, 'IsRebate' => 1]);
                                    } else {
                                        $memBalances = $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances]);
                                    }
                                }
                                //已完成销售金额
                                //   $toalMoneyTwo = $moneyTwo + $entMemberDRPTree->FinishMoney;
                                //会员余额
                                // $MemBalancesTwo=$entMemberDRPTree->MemBalances+$moneyTwo;
                                //  DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['FinishMoney' => $toalMoneyTwo,'MemBalances' => $MemBalancesTwo]);
                                $IsFinishTwo = 0;
                                if ($entMemberDRPTree->IsRebate == 1) {
                                    $IsFinishTwo = 1;
                                }
                                $entPushMoneyLogTwo = new EntPushMoneyLog();
                                $entPushMoneyLogTwo->MemNumber = $entMemberDRPTree->MemNumber;
                                $entPushMoneyLogTwo->Scale = $this->scaleTwo;
                                $entPushMoneyLogTwo->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLogTwo->PayMoney = $moneyTwo;
                                $entPushMoneyLogTwo->IsFinish = $IsFinishTwo;
                                $entPushMoneyLogTwo->MemberType = 1;
                                $entPushMoneyLogTwo->ToMemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLogTwo->PushMoneyDesc = '下线合伙人发展新会员提点5%';
                                $entPushMoneyLogTwo->DeleteMark = 1;
                                $entPushMoneyLogTwo->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->save();
                            }
                        }
                    }
                }
            }
        }
    }
}